import { GET_TOKEN } from "@/utils/token";
import { createRouter,createWebHistory } from "vue-router";

// 定义路由关系
const routes = [
  {
    path:'/login',
    // 路由懒加载
    component:()=>import('@/views/Login.vue')
  },
  {
    path:'/',
    component:()=>import('@/views/Layout.vue'),
    redirect:'/article/category',
    children:[
      {
        path:'/article/category',
        component:()=>import('@/views/article/ArticleCategory.vue')
      },
      {
        path:'/article/manage',
        component:()=>import('@/views/article/ArticleManage.vue')
      },
      {
        path:'/user/info',
        component:()=>import('@/views/user/UserInfo.vue')
      },
      {
        path:'/user/avatar',
        component:()=>import('@/views/user/UserAvatar.vue')
      },
      {
        path:'/user/resetPassword',
        component:()=>import('@/views/user/UserResetPassword.vue')
      }
    ]
  }
]

// 创建路由器
const router = createRouter({
  routes,
  // TODO:去掉路径当中的#号【待解决3】
  // 解决：浏览器模式使用createWebHistory
  history: createWebHistory(),
  // 实现功能:在不同路由切换的时候，可以自动滚动到页面的顶部，而不是停留在原先的位置
  scrollBehavior(){
    return {
      top:0
    }
  }
})

// 配置全局前置路由守卫
router.beforeEach((to,from,next)=>{
  if(to.path=='/login'){
    return next()
  }
  const token = GET_TOKEN()
  if(!token){
    // 未登录
    return next('/login')
  }
  next()
})

// 默认导出
export default router